<template>
  <div class="app-container mytree">

    <!-- <el-tree
      :data="treeData"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      :render-content="renderContent"
    /> -->

    <el-tree
      :data="treeData"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
    >
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <span>{{ data.name }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            class="mangerName"
            @click="() => append(data,node)"
          >    {{ data.managerName }}</el-button>

          <el-dropdown @command="getCtrl">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="'add'+'-'+data.id"> 添加子部门</el-dropdown-item>
              <el-dropdown-item :command="'edit'+'-'+data.id">编辑部门</el-dropdown-item>
              <el-dropdown-item :command="'del'+'-'+data.id">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="diaTitle" width="50%" :visible.sync="addFlag">
      <el-form
        ref="mydepartForm"
        label-width="100px"
        style="padding:0 40px;box-sizing: border-box;"
        :rules="rules"
        :model="departObj"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departObj.name" />
        </el-form-item>

        <el-form-item label="部门编码" prop="code">
          <el-input v-model="departObj.code" />
        </el-form-item>

        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="departObj.managerId">
            <el-option
              v-for="item in departList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="departObj.introduce" type="textarea" placeholder="1-100字" />
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="toAdd">确定</el-button>
        <el-button type="danger" @click="toClose">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentApi, getDepartApi, addDepartApi, delDepartment, getNowDepart, updateDepartment } from '@/api/social'
export default {

  data() {
    return {
      diaTitle: '新增部门',
      socialList: [], // 部门数据 树型需要的数据
      addFlag: false, // 添加和编辑部门的弹出层控制
      departList: [], // 部门负责人列表
      tabindex: 0,
      rules: { // 表单的验证规则
        code: [{ required: true, message: '部门编码必填', trigger: 'blur' }],
        introduce: [
          { required: true, message: '部门描述必填', trigger: 'blur' },
          {
            min: 1, max: 100, message: '描述在1-100之间', trigger: 'blur'
          }],
        managerId: [{ required: true, message: '部门负责人必填', trigger: 'blur' }],
        name: [{ required: true, message: '部门名称必填', trigger: 'blur' }]

      },
      departObj: { // 表单的v-model数据字段
        pid: '', // 正在添加字母部门或编辑部门的 id
        code: '', // 部门编码
        introduce: '', // 描述
        managerId: '', // 部门负责人id
        name: ''// 部门名称
      }
    }
  },
  computed: {
    //
    treeData() {
      // 根据返回的树形数据 处理成  el-tree组件需要的数据
      // 根据数据中pid字段 来进行分类
      const arr = this.toTree(this.socialList)
      console.log(arr, '$$$$$$$$$$$$$$$$$$$$')

      return arr
    }

  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val)
    },
    addFlag(newVal) { // 弹出层的控制变量
      if (!newVal) {
        this.departObj = { // 表单的v-model数据字段
          pid: '', // 正在添加字母部门或编辑部门的 id
          code: '', // 部门编码
          introduce: '', // 描述
          managerId: '', // 部门负责人id
          name: ''// 部门名称
        }
        this.diaTitle = '新增部门'
      }
    }
  },
  created() {
    this.getSocial()
  },
  methods: {
    toClose() { // 点击取消 清空数据
      this.addFlag = false
    },
    async toAdd() { // 添加接口 和  编辑接口
      // 表单自带的验证方法
      this.$refs.mydepartForm.validate(async(vali) => {
        if (vali) {
          if (this.departObj.id) { // 编辑接口
            const upRes = await updateDepartment(this.departObj)
            console.log(upRes, '^^^^^^^^^^^^^^^')
            this.$message.success('编辑部门成功')
          } else {
            const res = await addDepartApi(this.departObj) // 添加接口
            console.log(res, '-----------------')
            this.$message.success('添加部门成功')
          }
          this.addFlag = false// 关闭遮罩层
          this.$refs.mydepartForm.resetFields() // 表单自带清空方法
          this.getSocial()// 添加成功 重新获取列表
        }
      })
    },
    async getCtrl(ctrlText) { // 下拉菜单的选择事件
      console.log(ctrlText, '##################') // add-7   edit-9
      const arr = ctrlText.split('-')
      // 获取部门负责人列表
      const res = await getDepartApi()
      console.log(res, '---------------')
      this.departList = res

      // 存储正在编辑的部门父级id
      this.departObj.pid = arr[1]
      if (arr[0] === 'add') {
        this.addFlag = true
        this.diaTitle = '添加部门'

        console.log('添加')
      }
      if (arr[0] === 'edit') { // 下拉菜单点击了编辑
        this.addFlag = true
        this.diaTitle = '编辑部门'
        // 根据id 获取当前编辑部门数据  进行回显
        const editRes = await getNowDepart(arr[1])
        console.log(editRes, '555555555555555555555555')
        this.departObj = editRes // 给v-model的数据  赋值就行回显 managerId 3
      }
      if (arr[0] === 'del') { // 下拉菜单 选择了删除  调用删除部门的接口
        console.log('去删除')
        this.$confirm('你确定删除这个部门吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          // 删除部门接口
          const delRes = await delDepartment(arr[1])
          console.log(delRes, '---------')
          this.$message.success('删除部门成功')
          this.getSocial()// 删除成功后 重新调用列表
        })
      }
    },
    append(data, node) {
      console.log(data, node)
    },
    async   getSocial() { // 获取数树型部门的接口数据
      const res = await getDepartmentApi()

      console.log(res, '66666666666666666')
      this.socialList = res
      // 相同父级部门的数据要放在相同的children
    },
    toTree(data) { // 树形处理数据插件
      const result = []
      if (!Array.isArray(data)) {
        return result
      }
      data.forEach(item => {
        delete item.children
      })
      const map = {}
      data.forEach(item => {
        map[item.id] = item
      })
      data.forEach(item => {
        const parent = map[item.pid]
        if (parent) {
          (parent.children || (parent.children = [])).push(item)
        } else {
          result.push(item)
        }
      })
      return result
    },
    renderContent(h, { node, data, store }) {
      return (<span class='custom-tree-node'>
        <span>{node.label}</span>
        <span>
          <el-button size='mini' type='text' >Append</el-button>
          <el-button size='mini' type='text'>Delete</el-button>
        </span>
      </span>)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
  }
}
</script>
<style lang="scss" scoped>
.el-tree ::v-deep .custom-tree-node {
  width:900px;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .mytree{
    padding:0 50px;
    box-sizing:border-box;
  }
  .mangerName{
    margin-right:20px;
  }
</style>

